package com.celebracion;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;


import com.celebracion.util.CameraUtil;
import com.celebracion.util.DBUtil;
import com.celebracion.util.FileUtil;
import com.celebracion.util.SystemUiHider;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


public class FotoActivity extends Activity {
	 private Camera mCamera;
	 private CameraPreview mPreview;
	 private String fileTemp;
	 private FrameLayout preview; 
	 LinearLayout layout ;
	 TextView tvCuentaAtras;
	 Button btnHacerFoto;
	
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_foto2);
	    // Create an instance of Camera
	    mCamera = CameraUtil.getCameraInstance();
	    layout = (LinearLayout)findViewById(R.id.foto2Layout);
        btnHacerFoto=(Button)findViewById(R.id.btnHacerFoto);
        tvCuentaAtras = (TextView) findViewById(R.id.tvCuentaAtras);
	    // Create our Preview view and set it as the content of our activity.
	    mPreview = new CameraPreview(this, mCamera);
	    mPreview.setDrawingCacheEnabled(true);
	   
	    layout.addView(mPreview);
	  
	}
	
	@Override
    protected void onDestroy() {
    	super.onDestroy();
    	mCamera.release();
    }
	
	public void atras(View v){
	    	finish();
	 }
	
	public void makePhoto(View view){
		new Thread(new Runnable() {
			public void run() {

				layout.post(new Runnable() {
					@Override
					public void run() {
						tvCuentaAtras.setVisibility(View.VISIBLE);
						btnHacerFoto.setVisibility(View.GONE);
					}
				});

				for (int i = 5; i >= 0; i--) {
					layout.post(new CountDownRunnable(i) {
						@Override
						public void run() {
							tvCuentaAtras.setVisibility(View.VISIBLE);
							tvCuentaAtras.setText(this.getCountDown() + "");
						}
					});
					delay(1000);
				}
				makeFotoAPI();
				layout.post(new Runnable() {
					@Override
					public void run() {
						tvCuentaAtras.setVisibility(View.GONE);
					}
				});
				
			}
		}).start();
		//layout.removeAllViews();
		
	
		//this.finish();
		
		
	}
	
	private void makeFotoAPI(){
		/*Log.d("intentImage", "intentImage");
		 Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
		    startActivityForResult(cameraIntent, 567); */
		mCamera.takePicture(null,null,  
			new PictureCallback(){

			@Override
			public void onPictureTaken(byte[] data, Camera camera) {
				 File pictureFile = FileUtil.getInternalFile(FileUtil.MEDIA_TYPE_IMAGE, DBUtil.getInstance(FotoActivity.this.getBaseContext()).getEventoActivo().getId(),FileUtil.DIRECTORIO_APP_TEMP,FotoActivity.this.getBaseContext());
			        if (pictureFile == null){
			            Log.d("hacerFoto", "Error creating media file, check storage permissions: " );
			            return;
			        }

			        try {
			        	FileOutputStream fos = new FileOutputStream(pictureFile);
			            fos.write(data);
     		            fos.close();
			            Intent intent=new Intent(FotoActivity.this,FotoPreviewActivity.class);
						intent.putExtra("foto",pictureFile.toString());
						startActivity(intent);
			        } catch (FileNotFoundException e) {
			            Log.d("hacerFoto", "File not found: " + e.getMessage());
			        } catch (IOException e) {
			            Log.d("hacerFoto", "Error accessing file: " + e.getMessage());
			        }
				    
			}});
		
		
	}
	
	public void saveFoto(View view){
	
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		// 2. Chain together various setter methods to set the dialog characteristics
		builder.setMessage(R.string.askSaveFoto)
		       .setTitle(R.string.askTitleSaveFoto);
		// Add the buttons
		builder.setPositiveButton(R.string.Si, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   FileUtil.saveTempToFile(fileTemp, DBUtil.getInstance(FotoActivity.this.getBaseContext()).getEventoActivo().getId(),FotoActivity.this.getBaseContext());
		        	   Toast.makeText(FotoActivity.this, R.string.fotoSaved, Toast.LENGTH_SHORT).show();
		           }
		       });
		builder.setNegativeButton(R.string.No, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		               // User cancelled the dialog
		           }
		       });
		// 3. Get the AlertDialog from create()
		AlertDialog dialog = builder.create();
		dialog.show();
	}
	
	public void deleteFoto(View view){
		FileUtil.deleteTempFile(fileTemp);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		// 2. Chain together various setter methods to set the dialog characteristics
		builder.setMessage(R.string.askDeleteFoto)
		       .setTitle(R.string.askTitleDeleteFoto);
		// Add the buttons
		builder.setPositiveButton(R.string.Si, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        		FileUtil.deleteTempFile(fileTemp);
		        	   Toast.makeText(FotoActivity.this, R.string.fotoDeleted, Toast.LENGTH_SHORT).show();
		           }
		       });
		builder.setNegativeButton(R.string.No, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		               // User cancelled the dialog
		           }
		       });
		// 3. Get the AlertDialog from create()
		AlertDialog dialog = builder.create();
		dialog.show();
		
	}
	
	void delay(int milliseconds) {
		try {
			Thread.sleep(milliseconds);
		} catch (InterruptedException e) {}
	}
	
	private abstract class CountDownRunnable implements Runnable {
		private int countDown;

		public CountDownRunnable(int a) {
			countDown = a;
		}

		public int getCountDown() {
			return countDown;
		}

	}
}
